#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

void create_shm(char* root, char* name, int size) {
    char file_name[256];
    sprintf(file_name, "%s/%s", root, name);

    int fd;
    if ((fd = creat(file_name, 0644)) < 0) {
        perror("could not create shared memory");
        exit(1);
    }

    if (ftruncate(fd, size) != 0) {
        perror("could not resize shared memory");
        exit(1);
    }

    close(fd);
}

void create_user_shm(char* root, char* name, int size) {
    char full_name[256];
    sprintf(full_name, "user/%s", name);

    create_shm(root, full_name, size);
}

void create_unit_shm(char* root, char* name, int size) {
    char full_name[256];
    sprintf(full_name, "unit/%s", name);

    create_shm(root, full_name, size);
}

int main(int argc, char* argv[]) {
    char* root = getenv("RELAT_ROOT");

    create_shm(root, "user_count", sizeof(unsigned));
    create_shm(root, "unit_count", sizeof(unsigned));

    create_user_shm(root, "name", 3 * sizeof(char) * 64);
    create_user_shm(root, "position", 3 * sizeof(double) * 3);

    create_unit_shm(root, "name", 5 * sizeof(char) *  64);
    create_unit_shm(root, "position", 5 * sizeof(double) * 3);
    create_unit_shm(root, "velocity", 5 * sizeof(double) * 3);
    create_unit_shm(root, "owner", 5 * sizeof(double));

    return 0;
}